package com.xmut.mall.manager.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;

import java.util.Calendar;
import java.util.Date;

@Slf4j
public class JWTUtils {

    //    @Value("${jwt.secret}")
    private static String secret = "8b363105-9b40-4275-9176-a7edf5aec0b0";
    private static Algorithm algorithm = Algorithm.HMAC256(secret);

    /**
     * 生成accesstoken
     *
     * @param userJson
     * @return
     */
    public static String createAccessToken(String userJson) {
        String accessToken = "";
        try {
            Calendar instance = Calendar.getInstance();
            instance.add(Calendar.MINUTE, 1);
            accessToken = JWT.create()
                    .withClaim("info", userJson)
                    .withExpiresAt(instance.getTime())
                    .withIssuedAt(new Date())
                    .sign(algorithm);
        } catch (JWTCreationException e) {
            e.printStackTrace();
        }
        return accessToken;
    }

    public static String createRefreshToken(String userJson) {
        String refreshToken = "";
        try {
            Calendar instance = Calendar.getInstance();
            instance.add(Calendar.MINUTE, 2);
            refreshToken = JWT.create()
                    .withClaim("info", userJson)
                    .withExpiresAt(instance.getTime())
                    .withIssuedAt(new Date())
                    .sign(algorithm);
        } catch (JWTCreationException e) {
            e.printStackTrace();
        }
        return refreshToken;
    }

    public static DecodedJWT verifyToken(String token) {
        return JWT.require(algorithm).build().verify(token);
    }

    public static String getClaim(String token) {
        String userInfo = "";
        try {
            userInfo = JWT.require(algorithm).build().verify(token).getClaim("info").asString();
        } catch (JWTVerificationException e) {
            e.printStackTrace();
        }
        return userInfo;
    }

    public static Boolean checkIsExpires(String token) {
        if (JWT.decode(token).getExpiresAt().getTime() < new Date().getTime()){
            return new Boolean(true);
        }else {
            return new Boolean(false);
        }

    }
}
